package com.taptech.doufu.ui.activity.me
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.telephony.PhoneNumberUtils
import android.widget.TextView
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.taptech.doufu.R
import com.taptech.doufu.constant.IntentKey
import com.taptech.doufu.event.LoginStateEvent
import com.taptech.doufu.ext.appToast
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.services.personalcenter.WeChatService
import com.taptech.doufu.ui.activity.BrowseActivity
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity
import com.taptech.doufu.ui.view.WaitDialog
import com.taptech.doufu.umeng.UVerifyManager
import com.taptech.doufu.util.CheckInfo
import com.taptech.doufu.weex.http.TFHttpUtil
import com.taptech.doufu.weex.notification.QLXNotificationCenter
import com.douhuayuedu.douhua.wxapi.WXEntryActivity
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.taptech.doufu.util.Md5Util
import kotlinx.android.synthetic.main.activity_phone_login.*
import rx.Observable
import java.util.concurrent.TimeUnit

class PhoneLoginActivity :DiaobaoBaseActivity(){

    lateinit var timer: CountDownTimer
    private var countryCode: Int = 86
    lateinit var waitDialog: WaitDialog
    var isSelectPrivacy:Boolean = false
    var canSend = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_phone_login)
        waitDialog = WaitDialog(this,R.style.updateDialog)

        timer = object : CountDownTimer(60000,1000){
            override fun onFinish() {
                tvSendMsgCode.text = getString(R.string.login_send_again)
                canSend = true
            }

            override fun onTick(millisUntilFinished: Long) {
                tvSendMsgCode.text = "${getString(R.string.login_send_again)} ${millisUntilFinished/1000}S"
            }
        }
        tvSendMsgCode.setOnClickListener {
            if (!canSend){
                return@setOnClickListener
            }
            canSend = false
            tvSendMsgCode.text = "发送中"
            sendMobileCode()
        }

        tvAgreement.setOnClickListener {
            BrowseActivity.startActivity(this, "https://api.douhuawenxue.com/journal/detail?id=794")
        }

        tvPrivacy.setOnClickListener {
            BrowseActivity.startActivity(this,"https://api.douhuawenxue.com/journal/detail?id=793")
        }

        tvHelp.setOnClickListener {
            var bottomDialog = BottomSheetDialog(this)
            bottomDialog.setContentView(R.layout.dialog_help)
            bottomDialog.findViewById<TextView>(R.id.tvAccount)?.setOnClickListener {
                BrowseActivity.startActivity(this,"https://api.doufuwenxue.com/journal/detail?id=809")
                bottomDialog.dismiss()
            }
            bottomDialog.findViewById<TextView>(R.id.tvOther)?.setOnClickListener {
                BrowseActivity.startActivity(this,"https://api.doufu.la/index.php/help/question")
                bottomDialog.dismiss()
            }
            bottomDialog.findViewById<TextView>(R.id.tvCancel)?.setOnClickListener {
                bottomDialog.dismiss()
            }
            bottomDialog.show()
        }

        tvSwitchToSimple.setOnClickListener {
            UVerifyManager.getInstance().verifyLogin(true)
            finish()
        }

        tvPasswordLogin.setOnClickListener {
            SimpleWeexActivity.startActivity(this, "vue/login/TFLoginRegister.js", Intent.FLAG_ACTIVITY_NEW_TASK)
        }

        ivWeChatLogin.setOnClickListener {
            if (!isSelectPrivacy) {
                appToast("请先同意用户协议与隐私政策")
                return@setOnClickListener
            }
            WXEntryActivity.pageType = WXEntryActivity.PAGE_TYPE_NATIVE_WECHAT
            WXEntryActivity.opType = WXEntryActivity.OP_TYPE_LOGIN_WECHAT
            WeChatService.getInstance(this).sendWeChatLogin()
        }

        laySelect.setOnClickListener {
            isSelectPrivacy = !isSelectPrivacy
            if (isSelectPrivacy) {
                ivSelect.setImageResource(R.drawable.icon_select_red)
            }else{
                ivSelect.setImageResource(R.drawable.icon_un_select)
            }
        }

        tvCountryCode.setOnClickListener {
            AreaCodeActivity.startActivityForResult(this)
        }
        tvLogin.setOnClickListener {
            mobileLogin()
        }

        QLXNotificationCenter.getInstance().addNotify("kTFUserDidLoginCompleteNotification", this) { _, _ ->
            finish()
        }

        Bus.observe<LoginStateEvent>()
            .subscribe{
                //登录成功，关闭页面
                if (it.isLogin) {
                    finish()
                }
            }.registerInBus(this)
    }

    private fun showLoadingDialog() {
        waitDialog.show()
    }

    private fun dismissLoadingDialog() {
        if (waitDialog.isShowing) {
            waitDialog.dismiss()
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                val num = data.getIntExtra(IntentKey.DATA, -1)
                countryCode = num
                tvCountryCode.text = "+${num}"
            }
        }
    }


    private fun checkPhone() :Boolean{
        if (etNumber.length() == 0) {
            appToast("手机号码不能为空")
            resetSendCodeBtnUI()
            return false
        }
//        if (!CheckInfo.isPhoneNumberValid("+${countryCode}${etNumber.text}","$countryCode")) {
//            appToast("请输入正确手机号")
//            resetSendCodeBtnUI()
//            return false
//        }
        return true
    }

    private fun getSign(mobile: String, code: Int, timestamp: Long):String {
        return Md5Util.getMD5Str("VfYFsJFKN41IkIs${mobile}${code}${timestamp}")
    }

    private fun sendMobileCode() {
        if (!checkPhone()) {
            return
        }
        if (!isSelectPrivacy) {
            appToast("请先同意用户协议与隐私政策")
            resetSendCodeBtnUI()
            return
        }
        var timestamp = System.currentTimeMillis()/1000
        var url = "/member/mobile_login_code"
        var params = mutableMapOf<String, Any>()
        params["mobile"] = "${etNumber.text}"
        params["country_code"] = "$countryCode"
        params["country_code"] = "$countryCode"
        params["timestamp"] = "$timestamp"
        params["sign"] = getSign(etNumber.text.toString(),countryCode,timestamp)
        TFHttpUtil.requestPost(url,params){json, error ->
            try {
                var status = json.getIntValue("status")
                if (status == 0) {
                    var data = json.getJSONObject("data")
                    if (data.getIntValue("affected") > 0) {
                        appToast("验证码发送成功")
                        //倒计时
                        timer.start()
                    }else{
                        appToast("验证码发送失败")
                        resetSendCodeBtnUI()
                    }
                } else {
                    //失败，提示
                    var message = json.getString("user_msg")
                    if (message != null) {
                        appToast(message)
                    } else {
                        appToast("验证码发送失败")
                    }
                    resetSendCodeBtnUI()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                appToast("验证码发送失败")
                resetSendCodeBtnUI()
            }
        }
    }

    private fun resetSendCodeBtnUI() {
        canSend = true
        tvSendMsgCode.text = "获取验证码"
    }

    private fun mobileLogin() {
        if (!checkPhone()) {
            return
        }
        if (etCode.text.isEmpty()) {
            appToast("请输入验证码")
            return
        }
        showLoadingDialog()
        var url = "/member/mobile_login"
        var params = mutableMapOf<String, Any>()
        params["mobile"] = "${etNumber.text}"
        params["country_code"] = "$countryCode"
        params["code"] = "${etCode.text}"
        TFHttpUtil.requestPost(url,params){json, error ->
            try {
                var status = json.getIntValue("status")
                if (status == 0) {
                    var data = json.getJSONObject("data")
                    AccountService.setAccountData(data.toJSONString(),null)
                    QLXNotificationCenter.getInstance()
                        .postNotify("kTFUserDidLoginCompleteNotification", null)
                    Bus.send(LoginStateEvent(true)) //相关页面监听到后刷新页面
                    Observable.timer(1000,TimeUnit.MILLISECONDS)
                        .subscribe {
                            finish()
                        }
                } else {
                    //失败，提示
                    var message = json.getString("user_msg")
                    if (message != null) {
                        appToast(message)
                    } else {
                        appToast("登录失败")
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                appToast("登录失败")
            }
            dismissLoadingDialog()
        }

    }


    companion object{
        fun startActivity(context: Context) {
            var intent = Intent()
            intent.setClass(context,PhoneLoginActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
    }


}